<template>
  <view class="page-container">
    <!-- 顶部栏 -->
    <view class="header cu-bar bg-white solid-bottom">
      <view class="action">
        <text class="cuIcon-back" @tap="goBack"></text>
        <text class="question-type">{{ getQuestionType }}</text>
      </view>
      <view class="action">
        <button class="card-btn" @tap="showCardModal">答题卡</button>
      </view>
    </view>

    <!-- 答题卡弹窗 -->
    <view class="cu-modal drawer-modal justify-end" :class="modalCard ? 'show' : ''" @tap="hideCardModal">
      <view class="cu-dialog basis-lg answer-card" @tap.stop>
        <view class="card-header">
          <text>答题卡</text>
        </view>
        <scroll-view class="card-content" scroll-y>
          <view class="grid col-5 padding-sm">
            <view class="margin-tb-sm text-center" v-for="(item, index) in subjectList" :key="index">
              <view class="num-btn" 
                :class="[
                  getAnswerStatus(item),
                  { current: index === subjectIndex }
                ]"
                @tap="jumpToQuestion(index)">
                <text class="num">{{ index + 1 }}</text>
                <text class="status">{{ getStatusText(item) }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 题目内容区域 -->
    <view v-if="loading" class="loading-container">
      <view class="cu-load loading"></view>
      <text>加载题目中...</text>
    </view>
    
    <view v-else-if="!subjectList.length" class="empty-container">
      <text>暂无题目</text>
    </view>
    
    <swiper v-else class="question-swiper" 
      :current="subjectIndex" 
      @change="handleSwiperChange"
      :style="{ height: swiperHeight }">
      <swiper-item v-for="(subject, index) in subjectList" :key="index">
        <scroll-view class="question-container" scroll-y>
          <!-- 题目标题 -->
          <view class="question-title">
            <text class="dot"></text>
            <text class="title-text">{{ index + 1 }}. {{ subject.title }}</text>
          </view>

          <!-- 选项区域 -->
          <view class="options-area">
            <radio-group v-if="subject.test_type === 1" @change="handleOptionChange">
              <label class="option-item" v-for="option in subject.optionList" :key="option.id"
                :class="{
                  'option-selected': isOptionSelected(subject, option.optionId),
                  'option-correct': subject.showAnswer && isOptionCorrect(subject, option.optionId),
                  'option-wrong': subject.showAnswer && isOptionWrong(subject, option.optionId)
                }">
                <radio :value="option.optionId" :checked="isOptionSelected(subject, option.optionId)" color="#4CAF50" />
                <text class="option-id">{{ option.optionId }}</text>
                <text class="option-content">{{ option.content }}</text>
              </label>
            </radio-group>

            <checkbox-group v-else @change="handleOptionChange">
              <label class="option-item" v-for="option in subject.optionList" :key="option.id"
                :class="{
                  'option-selected': isOptionSelected(subject, option.optionId),
                  'option-correct': subject.showAnswer && isOptionCorrect(subject, option.optionId),
                  'option-wrong': subject.showAnswer && isOptionWrong(subject, option.optionId)
                }">
                <checkbox :value="option.optionId" :checked="isOptionSelected(subject, option.optionId)" color="#4CAF50" />
                <text class="option-id">{{ option.optionId }}</text>
                <text class="option-content">{{ option.content }}</text>
              </label>
            </checkbox-group>

            <!-- 多选题提交按钮 -->
            <button v-if="subject.test_type === 2 && hasSelectedOptions(subject)" 
              class="submit-btn" 
              @tap="submitAnswer(subject)">
              提交答案
            </button>

            <!-- 答案解析 -->
            <view v-if="subject.showAnswer" class="answer-section">
              <view class="answer-title">
                <text>正确答案：</text>
                <text class="answer-text">{{ subject.answer }}</text>
              </view>
              <view class="explain-content" v-if="subject.explain">
                <text class="explain-label">解析：</text>
                <text class="explain-text">{{ subject.explain }}</text>
              </view>
            </view>

<!--            <button class="submit-btn" @tap="submitAnswer(subject)" :disabled="!canSubmit(subject)">提交答案</button> -->
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>

    <!-- 底部导航栏 -->
    <view class="footer cu-bar tabbar bg-white" v-if="subjectList.length">
      <view class="action" @tap="prevQuestion" :class="{ disabled: subjectIndex === 0 }">
        <text class="cuIcon-back"></text>
        <text>上一题</text>
      </view>
      <view class="action" @tap="nextQuestion" :class="{ disabled: subjectIndex === subjectList.length - 1 }">
        <text class="cuIcon-right"></text>
        <text>下一题</text>
      </view>
      <view class="action" @tap="toggleFavorite">
        <text class="cuIcon-favor" :class="{ 'text-red': currentSubject && currentSubject.userFavor }"></text>
        <text>{{ currentSubject && currentSubject.userFavor ? '取消收藏' : '收藏' }}</text>
      </view>
      <view class="action" @tap="submitPaper">
        <text class="cuIcon-roundcheck"></text>
        <text>交卷</text>
      </view>
    </view>
  </view>
</template>

<script>
import { listDetail } from '../../common/api.js';

export default {
  data() {
    return {
      loading: false,
      modalCard: false,
      categoryId: '',
      subjectList: [],
      subjectIndex: 0,
      swiperHeight: '100vh'
    }
  },

  computed: {
    getQuestionType() {
      const currentSubject = this.subjectList[this.subjectIndex];
      if (!currentSubject) return '';
      return currentSubject.test_type === 1 ? '单选题' : '多选题';
    },
    currentSubject() {
      return this.subjectList[this.subjectIndex];
    }
  },

  async onLoad(options) {
    console.log('页面参数:', options); // 添加日志
    
    // 检查是否已登录
    const token = uni.getStorageSync('token');
    if (!token) {
      uni.showModal({
        title: '提示',
        content: '请先登录',
        showCancel: false,
        success: () => {
          uni.navigateTo({
            url: '/pages/login/login'
          });
        }
      });
      return;
    }

    // 检查categoryId是否存在
    if (!options || !options.categoryId) {
      console.error('缺少categoryId参数');
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      });
      return;
    }

    this.categoryId = options.categoryId;
    console.log('设置categoryId:', this.categoryId);
    
    try {
      await this.loadQuestions();
    } catch (error) {
      console.error('加载题目出错:', error);
    }
    
    this.initPageHeight();
  },

  methods: {
    async loadQuestions() {
      if (this.loading) {
        console.log('正在加载中，跳过重复加载');
        return;
      }

      try {
        this.loading = true;
        console.log('开始加载题目, categoryId:', this.categoryId);
        
        const token = uni.getStorageSync('token');
        console.log('当前token:', token);
        
        if (!this.categoryId) {
          throw new Error('categoryId不能为空');
        }
        
        const [err, res] = await listDetail(this.categoryId);
        console.log('API响应:', err, res);
        
        if (err) {
          if (err.statusCode === 401) {
            uni.showModal({
              title: '提示',
              content: '登录已过期，请重新登录',
              showCancel: false,
              success: () => {
                uni.removeStorageSync('token');
                uni.navigateTo({
                  url: '/pages/login/login'
                });
              }
            });
            return;
          }
          
          throw err;
        }

        if (!res || !res.data) {
          throw new Error('响应数据为空');
        }

        // 获取实际的题目数据
        const questions = Array.isArray(res.data) ? res.data : res.data.data;
        
        if (!Array.isArray(questions)) {
          throw new Error('题目数据格式错误');
        }

        if (questions.length === 0) {
          uni.showToast({
            title: '暂无题目',
            icon: 'none'
          });
          return;
        }

        // 处理题目数据
        this.subjectList = questions.map(item => ({
          ...item,
          showAnswer: false,
          selectVal: Array.isArray(item.userAnswer) ? item.userAnswer : [],
          test_type: Number(item.test_type)
        }));
        
        console.log('题目加载成功，数量:', this.subjectList.length);
        console.log('处理后的题目数据:', this.subjectList);

      } catch (error) {
        console.error('加载题目失败:', error);
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none',
          duration: 3000
        });
        throw error;
      } finally {
        this.loading = false;
      }
    },

    showCardModal() {
      this.modalCard = true;
    },

    hideCardModal() {
      this.modalCard = false;
    },

    handleSwiperChange(e) {
      this.subjectIndex = e.detail.current;
    },

    jumpToQuestion(index) {
      this.subjectIndex = index;
      this.hideCardModal();
    },

    prevQuestion() {
      if (this.subjectIndex > 0) {
        this.subjectIndex--;
      }
    },

    nextQuestion() {
      if (this.subjectIndex < this.subjectList.length - 1) {
        this.subjectIndex++;
      }
    },

    toggleFavorite() {
      if (this.currentSubject) {
        this.currentSubject.userFavor = !this.currentSubject.userFavor;
      }
    },

    submitPaper() {
      uni.showModal({
        title: '提示',
        content: '确定要交卷吗？',
        success: (res) => {
          if (res.confirm) {
            // TODO: 实现交卷逻辑
            uni.navigateBack();
          }
        }
      });
    },

    getAnswerStatus(subject) {
      if (!subject.showAnswer) return '';
      const isCorrect = subject.userAnswer === subject.answer;
      return isCorrect ? 'correct' : 'wrong';
    },

    getStatusText(subject) {
      if (!subject.showAnswer) return '';
      return subject.userAnswer === subject.answer ? '√' : '×';
    },

    handleOptionChange(e) {
      const currentSubject = this.currentSubject;
      if (!currentSubject) return;

      const value = e.detail.value;
      console.log('选项变化:', value);

      if (currentSubject.test_type === 1) {
        // 单选题直接显示答案
        currentSubject.userAnswer = value;
        currentSubject.showAnswer = true;
      } else {
        // 多选题，只更新选中状态
        currentSubject.selectVal = Array.isArray(value) ? value : [value];
      }
    },

    submitAnswer(subject) {
      if (!subject.selectVal || !subject.selectVal.length) return;
      
      // 多选题答案处理
      subject.userAnswer = subject.selectVal.join('');
      subject.showAnswer = true;
      console.log('提交答案:', subject.userAnswer);
    },

    hasSelectedOptions(subject) {
      return subject && subject.selectVal && subject.selectVal.length > 0;
    },

    isOptionSelected(subject, optionId) {
      if (!subject) return false;
      
      if (subject.test_type === 1) {
        return subject.userAnswer === optionId;
      }
      
      // 多选题的选中状态
      if (subject.showAnswer) {
        return subject.userAnswer && subject.userAnswer.includes(optionId);
      }
      return subject.selectVal && subject.selectVal.includes(optionId);
    },

    isOptionCorrect(subject, optionId) {
      if (!subject || !subject.answer) return false;
      return subject.answer.includes(optionId);
    },

    isOptionWrong(subject, optionId) {
      if (!subject || !subject.showAnswer) return false;
      return this.isOptionSelected(subject, optionId) && !this.isOptionCorrect(subject, optionId);
    },

    initPageHeight() {
      const _this = this;
      uni.getSystemInfo({
        success(res) {
          let tempHeight = res.windowHeight;
          uni.createSelectorQuery()
            .select(".header")
            .boundingClientRect(data => {
              tempHeight -= data.height;
              uni.createSelectorQuery()
                .select(".footer")
                .boundingClientRect(data => {
                  tempHeight -= data.height;
                  _this.swiperHeight = tempHeight + 'px';
                })
                .exec();
            })
            .exec();
        }
      });
    },

    goBack() {
      uni.navigateBack({
        delta: 1
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.header {
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 1000;
  
  .cuIcon-back {
    font-size: 36rpx;
    margin-right: 20rpx;
    color: #333;
  }
  
  .question-type {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }
  
  .card-btn {
    font-size: 28rpx;
    color: #666;
    background: none;
    padding: 0;
    
    &::after {
      border: none;
    }
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 100rpx);
  
  .cu-load {
    margin-bottom: 20rpx;
  }
  
  text {
    color: #666;
    font-size: 28rpx;
  }
}

.empty-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 100rpx);
  
  text {
    color: #999;
    font-size: 32rpx;
  }
}

.question-swiper {
  flex: 1;
  margin-top: 90rpx;
}

.question-container {
  height: 100%;
  padding: 30rpx;
  box-sizing: border-box;
}

.question-title {
  display: flex;
  align-items: flex-start;
  margin-bottom: 40rpx;
  
  .dot {
    width: 12rpx;
    height: 12rpx;
    border-radius: 50%;
    background: #4CAF50;
    margin: 16rpx 16rpx 0 0;
  }
  
  .title-text {
    flex: 1;
    font-size: 32rpx;
    line-height: 1.6;
    color: #333;
  }
}

.options-area {
  .option-item {
    display: flex;
    align-items: center;
    padding: 24rpx;
    margin-bottom: 24rpx;
    background: #fff;
    border-radius: 12rpx;
    transition: all 0.3s ease;
    
    &.option-selected {
      background: #E8F5E9;
      border: 2rpx solid #4CAF50;
    }
    
    &.option-correct {
      background: #E8F5E9;
      border: 2rpx solid #4CAF50;
    }
    
    &.option-wrong {
      background: #FFEBEE;
      border: 2rpx solid #F44336;
    }
    
    .option-id {
      width: 48rpx;
      height: 48rpx;
      line-height: 48rpx;
      text-align: center;
      background: #f5f5f5;
      border-radius: 50%;
      margin: 0 20rpx;
      font-weight: 500;
      color: #333;
    }
    
    .option-content {
      flex: 1;
      font-size: 30rpx;
      color: #333;
    }
  }

  .submit-btn {
    margin-top: 40rpx;
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    background: #4CAF50;
    color: white;
    border-radius: 8rpx;
    font-size: 32rpx;
  }
}

.answer-section {
  margin-top: 40rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 12rpx;
  
  .answer-title {
    margin-bottom: 20rpx;
    
    text {
      font-size: 30rpx;
      
      &.answer-text {
        color: #4CAF50;
        font-weight: 500;
      }
    }
  }
  
  .explain-content {
    .explain-label {
      font-size: 30rpx;
      color: #666;
      margin-bottom: 16rpx;
      display: block;
    }
    
    .explain-text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }
  }
}

.footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  padding-bottom: env(safe-area-inset-bottom);
  
  .action {
    flex: 1;
    text-align: center;
    
    &.disabled {
      opacity: 0.5;
    }
    
    text {
      font-size: 24rpx;
      color: #666;
      display: block;
      
      &:first-child {
        font-size: 40rpx;
        margin-bottom: 4rpx;
      }
      
      &.text-red {
        color: #f44336;
      }
    }
  }
}

.answer-card {
  height: 80vh;
  display: flex;
  flex-direction: column;
  
  .card-header {
    padding: 30rpx;
    text-align: center;
    border-bottom: 1rpx solid #eee;
    
    text {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
    }
  }
  
  .card-content {
    flex: 1;
    padding: 30rpx;
    
    .num-btn {
      width: 80rpx;
      height: 80rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: #f5f5f5;
      border-radius: 12rpx;
      
      &.current {
        background: #4CAF50;
        
        .num, .status {
          color: #fff;
        }
      }
      
      &.correct {
        background: #E8F5E9;
        border: 2rpx solid #4CAF50;
      }
      
      &.wrong {
        background: #FFEBEE;
        border: 2rpx solid #F44336;
      }
      
      .num {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
      
      .status {
        font-size: 24rpx;
        color: #666;
        margin-top: 4rpx;
      }
    }
  }
}
</style>